package org.jeecg.modules.my.roleApp.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.my.menghApp.entity.MenghApp;
import org.jeecg.modules.my.menghApp.service.IMenghAppService;
import org.jeecg.modules.my.roleApp.entity.RoleApp;
import org.jeecg.modules.my.roleApp.service.IRoleAppService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 角色和app
 * @Author: jeecg-boot
 * @Date: 2023-02-22
 * @Version: V1.0
 */
@Api(tags = "角色和app")
@RestController
@RequestMapping("/roleApp/roleApp")
@Slf4j
public class RoleAppController extends JeecgController<RoleApp, IRoleAppService> {
	@Autowired
	IMenghAppService menghAppService;

    @Autowired
    private IRoleAppService roleAppService;

    @GetMapping(value = "/getListByRoleIds")
    public Result<?> getListByRoleIds(String roleIds,
                                      String appName,
									  String appType,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
    	List<MenghApp> resultList = new ArrayList<>();
        List<MenghApp> newResultList = new ArrayList<>();

		for (String roleId: roleIds.split(",")
			 ) {
			List<RoleApp> list = roleAppService.list(new LambdaQueryWrapper<RoleApp>().eq(RoleApp::getRoleid, roleId));
			list.forEach(item -> {
				MenghApp menghApp = menghAppService.getById(item.getAppid());
				if(menghApp != null)
					resultList.add(menghApp);
			});
		}



		Page<MenghApp> page = new Page<MenghApp>(pageNo, pageSize);
		IPage<MenghApp> pageList = new Page<>();

        if(appName != null && appType != null) {
            newResultList = resultList.stream().filter(app -> app.getName().contains(appName) && app.getLeix().equals(appType)).collect(Collectors.toList());
            pageList.setRecords(newResultList);
            pageList.setTotal(newResultList.size());

            return Result.OK(pageList);
        }

        if(appName != null) {
            newResultList = resultList.stream().filter(app -> app.getName().contains(appName)).collect(Collectors.toList());
            pageList.setRecords(newResultList);
            pageList.setTotal(newResultList.size());

            return Result.OK(pageList);
        }

        if(appType != null) {
            newResultList = resultList.stream().filter(app -> app.getLeix().equals(appType)).collect(Collectors.toList());
            pageList.setRecords(newResultList);
            pageList.setTotal(newResultList.size());

            return Result.OK(pageList);
        }

		pageList.setRecords(resultList);
		pageList.setTotal(resultList.size());

		return Result.OK(pageList);

    }

    /**
     * 分页列表查询
     *
     * @param roleApp
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "角色和app-分页列表查询")
    @ApiOperation(value = "角色和app-分页列表查询", notes = "角色和app-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(RoleApp roleApp,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<RoleApp> queryWrapper = QueryGenerator.initQueryWrapper(roleApp, req.getParameterMap());
        Page<RoleApp> page = new Page<RoleApp>(pageNo, pageSize);
        IPage<RoleApp> pageList = roleAppService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param roleApp
     * @return
     */
    @AutoLog(value = "角色和app-添加")
    @ApiOperation(value = "角色和app-添加", notes = "角色和app-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody RoleApp roleApp) {
        List<RoleApp> batchList = new ArrayList<>();
        String[] appList = roleApp.getAppList().split(",");
        for (String appId : appList
        ) {
            RoleApp roleApp_tmp = new RoleApp();
            roleApp_tmp.setRoleid(roleApp.getRoleid());
            roleApp_tmp.setAppid(appId);

            MenghApp menghApp = menghAppService.getById(roleApp_tmp.getAppid());
            if (menghApp != null)
                roleApp_tmp.setType(menghApp.getLeix());

            batchList.add(roleApp_tmp);
        }

        roleAppService.saveBatch(batchList);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param roleApp
     * @return
     */
    @AutoLog(value = "角色和app-编辑")
    @ApiOperation(value = "角色和app-编辑", notes = "角色和app-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody RoleApp roleApp) {
        roleAppService.updateById(roleApp);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "角色和app-通过id删除")
    @ApiOperation(value = "角色和app-通过id删除", notes = "角色和app-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        roleAppService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "角色和app-批量删除")
    @ApiOperation(value = "角色和app-批量删除", notes = "角色和app-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.roleAppService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "角色和app-通过id查询")
    @ApiOperation(value = "角色和app-通过id查询", notes = "角色和app-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        RoleApp roleApp = roleAppService.getById(id);
        if (roleApp == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(roleApp);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param roleApp
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RoleApp roleApp) {
        return super.exportXls(request, roleApp, RoleApp.class, "角色和app");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, RoleApp.class);
    }

}
